package com.mojo.concurrent.concurrent_02_lock;

/**
 * happens-before规则示例
 *
 * @author <a href="mailto:sjj@jianzhimao.com">mojo</a>
 * copyright (C), 2013-2022, 广州九尾信息科技有限公司
 * @date 2022/3/15 16:44
 */
public class HappensBeforeDemo {
    private int n = 0;
    Object block = new Object();

    public synchronized void write() {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        n++;
        System.out.println(Thread.currentThread().getName() + "write complete");
    }

    public void read() {
        synchronized (this) {
            int i = n;
            System.out.println(i);
        }
    }

    public static void main(String[] args) {
        HappensBeforeDemo demo = new HappensBeforeDemo();

        Thread t1 = new Thread(() -> {
            demo.write();
        });
        Thread t2 = new Thread(() -> demo.read());
        t1.start();
        t2.start();
    }
    /* 执行结果
     * Thread-0write complete
     * 1
     * 验证了,使用同一个对象锁时
     */

}
